//
//  OrderViewController.m
//  体育商城
//
//  Created by  on 2022/9/24.
//

#import "OrderViewController.h"
#import "RefundsViewController.h"
#import "OrderPopViewController.h"
#import "OrderCell.h"
#import "RefundPopViewController.h"
#import "SubmitOrderViewController.h"

@interface OrderViewController ()
@property (strong, nonatomic) IBOutlet SegView *segView;
@property (strong, nonatomic) IBOutlet UIView *nodataView;
@property (strong, nonatomic)  NSMutableArray <Goods *> *array;
@property (copy, nonatomic)  NSString * selectType;

@end

@implementation OrderViewController

-  (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData: LS(@"全部")];
    [self initUI];
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self.view bringSubviewToFront:self.nodataView];
}
- (void)initUI{
    self.title = LS(@"我的订单");
    WS(self)
    self.segView.titles = @[@"全部",@"待付款",@"待发货",@"待收货",@"退款/售后"];
    self.segView.block = ^(NSString * _Nonnull text) {
        [weakself loadData:text];
    };
    self.tableViewStyle = UITableViewStylePlain;
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView registerNib:[OrderCell nib] forCellReuseIdentifier:[OrderCell ID]];
    NSLayoutConstraint *top = [self.tableView a1:NSLayoutAttributeTop e:NSLayoutRelationEqual t:self.segView a2:NSLayoutAttributeBottom c: 15];
    NSLayoutConstraint *left = [self.tableView a1:NSLayoutAttributeLeft e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeLeft c:15];
    NSLayoutConstraint *right = [self.tableView a1:NSLayoutAttributeRight e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeRight c:-15];
    NSLayoutConstraint *bottom = [self.tableView a1:NSLayoutAttributeBottom e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeBottom c:0];
    [self.view addConstraints:@[top,left,right,bottom]];
}
- (void)loadData:(NSString *)text{
    GoodsOrderStastus states;
    self.selectType = text;
    if ([text isEqualToString:LS(@"全部")]) {
        states = GoodsOrderStastusDefault;
    }else if ([text isEqualToString:LS(@"待付款")]){
        states = GoodsOrderStastusJoinCart;
    }else if ([text isEqualToString:LS(@"待发货")]){
        states = GoodsOrderStastusPayed;
    }else if ([text isEqualToString:LS(@"待收货")]){
        states = GoodsOrderStastusNoReceipt;
    }else if ([text isEqualToString:LS(@"退款/售后")]){
        states = GoodsOrderStastusAfterSales;
    }else{ }
    
    if (states == GoodsOrderStastusDefault) {
        [Goods bg_findAllAsync:nil complete:^(NSArray * _Nullable array) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.array = [NSMutableArray arrayWithArray:array];
            });
        }];
    }else{
        [GoodsTool find:states complete:^(NSArray<Goods *> * _Nonnull result) {
            self.array = [NSMutableArray arrayWithArray:result];
        }];
    }
}
- (void)setArray:(NSMutableArray<Goods *> *)array{
    _array = array;
    [self.tableView reloadData];
    self.nodataView.hidden =  array.count > 0;
}

- (void)action:(NSString *)text goods:(Goods*)good{
    if (APP.user.account ==  nil || APP.user.account.length <= 0) {
        return [Toast msg:LS(@"您还未登录，请先去登录")];
    }
    if ([text isEqualToString:LS(@"联系商家")]) {
        
    }else if ([text isEqualToString:LS(@"我要退款")]){
        [AlertPopViewController pop:LS(@"退款(无需退货)") content:@"" type:AlertPopViewControllerTypeInput block:^(int tag, NSString * _Nonnull text) {
            [GoodsTool delete:good complete:^{
                good.account = APP.user.account;
                good.orderID = [NSDate currentTimeStamp:@"yyyy/MM/dd HH:mm:ss"];
                good.orderStatus = GoodsOrderStastusAfterSales;
                [good bg_saveOrUpdateAsync:^(BOOL isSuccess) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:notifyJoinCartUpdate object:nil];
                    });
                }];
            }];
        }];
    }else if ([text isEqualToString:LS(@"我要退货退款")]){
        RefundsViewController *vc = [RefundsViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([text isEqualToString:LS(@"商店")]){
        
    }else if ([text isEqualToString:LS(@"去付款")]){
        SubmitOrderViewController * vc = [SubmitOrderViewController new];
        vc.model = good;
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([text isEqualToString:LS(@"催发货")]){
        OrderPopViewController *vc = [OrderPopViewController new];
        vc.style = OrderPopStyleShip;
        [self presentViewController:vc animated:YES completion:nil];
    }else if ([text isEqualToString:LS(@"修改地址")]){
        AddressManagerViewController *vc = [AddressManagerViewController new];
        vc.selectAddress = good.address;
        WS(self)
        vc.block = ^(Address * _Nonnull address) {
            good.address = address;
            [good bg_saveOrUpdateAsync:^(BOOL isSuccess) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:notifyJoinCartUpdate object:nil];
                });
            }];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([text isEqualToString:LS(@"退款状态")]){
        OrderPopViewController *vc = [OrderPopViewController new];
        vc.style = OrderPopStyleRefundSuccess;
        [self presentViewController:vc animated:YES completion:nil];
    }else if ([text isEqualToString:LS(@"确认收货")]){
        [GoodsTool delete:good complete:^{
            good.account = APP.user.account;
            good.orderID = [NSDate currentTimeStamp:@"yyyy/MM/dd HH:mm:ss"];
            good.orderStatus = GoodsOrderStastusAfterSales;
            [good bg_saveOrUpdateAsync:^(BOOL isSuccess) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:notifyJoinCartUpdate object:nil];
                });
            }];
        }];
    }else if ([text isEqualToString:LS(@"退款")]){
        RefundPopViewController *vc = [RefundPopViewController new];
        WS(self)
        vc.block = ^(NSString * _Nonnull text) {
            [weakself action:text goods:good];
        };
        [self presentViewController:vc animated:YES completion:nil];
    }else if ([text isEqualToString:LS(@"加入购物车")]){
        
    }else if ([text isEqualToString:LS(@"取消")] || [text isEqualToString:LS(@"删除记录")]){
        [AlertPopViewController pop:LS(@"提示") content:LS(@"确认删除该订单吗?") type:AlertPopViewControllerTypeCancel block:^(int tag, NSString * _Nonnull text) {
            [GoodsTool delete:good complete:^{
                [[NSNotificationCenter defaultCenter] postNotificationName:notifyJoinCartUpdate object:nil];
            }];
        }];
    }
}
- (void)addNotify{
    [super addNotify];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateData) name:notifyJoinCartUpdate object:nil];
}
- (void)updateData{
    [self loadData:self.selectType];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.array.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    OrderCell *cell = [tableView dequeueReusableCellWithIdentifier:[OrderCell ID]];
    WS(self)
    cell.model = self.array[indexPath.section];
    if (cell.task) {
        [cell.task cancel];
    }
    cell.block = ^(NSString * _Nonnull text) {
        [weakself action:text goods:weakself.array[indexPath.section]];
    };
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return section == 0 ? 0 : 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return section == self.array.count - 1 ? 20 : 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

@end
